import datetime
import hashlib
import json
import time
from os import abort

import urllib3
# from bson import json_util 11111111112222
from flask import (
    redirect,
    render_template,
    request,
    make_response,
    jsonify,
    Blueprint
)
from pymongo import DESCENDING
# from wechatpy.exceptions import InvalidSignatureException, InvalidAppIdException
# from wechatpy.utils import check_signature
from wechatpy import create_reply, parse_message
from wechatpy.crypto import WeChatCrypto
from wechatpy.exceptions import InvalidSignatureException, InvalidAppIdException
from wechatpy.utils import check_signature

from app import Log
from app.response import ResponseError
from app.routes import Route
from app.routes.websocket_route import socketIo, add_one_message, namespace
from app.session import get_session, set_session, redis, get_token
from config.config import (WX, Base, QCloud, AES_KEY, APPID)
from service import redis_service, mongo_service, WAY_POINT, third_service, ThirdService
# from wechatpy import parse_message, create_reply
from urllib.parse import quote
from PIL import Image
from util.lib.TIME import TIME

name = 'wx'
wx_http_route = Blueprint(name, __name__, template_folder=Base.templateUrl)
logger = Log(name).init()
route = Route(name)
try_catch = route.try_catch


# http://weixin.pbani.com/wx/index


@wx_http_route.route('/index', methods=["GET"])
@try_catch
def index():
    logger.info('test')
    action = request.args.get('action', 'view_device')
    device_id = request.args.get('device_id', '')

    openid = request.cookies.get('pbani_o', '')
    save_openid_last_time = int(request.cookies.get('pbani_o_last_time', TIME.time()))

    print("save_openid_last_time", save_openid_last_time)
    print("diff", TIME.time() - save_openid_last_time)

    if TIME.time() - save_openid_last_time >= 86000:
        # if TIME.time() - save_openid_last_time >= 1:
        openid = ''

    logger.debug('cookie----' + openid)
    if not openid:
        url = Base.baseUrl + "/login_callback?" + "action=" + action + "&device_id=" + device_id
        callback_url = quote(url)
        login_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + \
                    WX.get('appid') + "&redirect_uri=" + \
                    callback_url + "&response_type=code&scope=snsapi_userinfo&state=STATE"
        return redirect(login_url)
    return render_index(action, openid, device_id)


@wx_http_route.route('/login_callback', methods=["GET"])
@try_catch
def login_callback():
    action = request.args.get('action')
    device_id = request.args.get('device_id', '')
    code = request.args.get('code', None)
    print('code', code)
    oauth = redis_service.oauth
    oauth_obj = oauth.fetch_access_token(code)
    print('oauth_obj', oauth_obj)
    openid = oauth_obj.get('openid', '')
    print('openid', openid)
    redis_service.session.set("openid", openid)

    access_token = oauth_obj.get('access_token')
    print('access_token', access_token)
    info = oauth.get_user_info()
    print('info', info)
    mongo_service.update('users', {
        'openid': openid
    }, {'$set': info}, True)

    resp = render_index(action, openid, device_id)
    return resp


def render_index(action, openid, device_id):
    # redis_service.post_template_of_unread_message(openid, "xxxx", int(time.time()), 3)

    if device_id:
        set_session('ctl', device_id)
        mongo_service.update('users', {
            'openid': openid
        }, {'$set': {
            'ctl': device_id
        }})

    resp = make_response(render_template(
        'index.html',
        token=openid,
        action=action
    ))
    resp.set_cookie('pbani_o', openid)
    resp.set_cookie('pbani_o_last_time', TIME.now())
    return resp


@wx_http_route.route('/screen_capture', methods=["GET"])
@try_catch
def screen_capture():
    sn = request.args.get('sn', '')
    if not sn:
        raise BaseException('no sn')

    res_json = third_service.browser_get('print_screen', {
        'deviceId': sn
    })
    if 'err' in res_json and res_json['err'] == 0:
        mongo_service.update('devices', {
            'sn': sn
        }, {'$set': {
            'status': 2
        }})

    return jsonify(res_json)


@wx_http_route.route('/login_for_test', methods=["GET"])
@try_catch
def login_for_test():
    openid = 'ohCrk0n71n3XgCObuwgSgmWLJpae'
    action = request.args.get('action', 'view_device')
    set_session('openid', openid)
    set_session('action', action)
    return jsonify({
        'err': 0
    })


@wx_http_route.route('/get_user_info', methods=["GET"])
@try_catch
def get_user_info():
    openid = get_token()
    if openid == '{{ token }}':
        openid = 'oYsiN0Qy-4rFukbNMGAIj8X70Xso'

    logger.info(openid)
    info = mongo_service.find_one('users', {
        "openid": openid
    })
    ctl = info.get('ctl', '')
    if not ctl:
        page = 'add_device'
    else:
        page = get_session('action')

    set_session('ctl', ctl)

    return jsonify({
        'info': mongo_service.toJsonStr(info),
        'page': page
    })


@wx_http_route.route('/change_device', methods=["GET"])
@try_catch
def change_device():
    sn = request.args.get('sn', '')

    if not sn:
        raise BaseException('no sn')

    openid = get_token()

    res = mongo_service.update('users', {
        "openid": openid
    }, {'$set': {
        'ctl': sn
    }})
    logger.info("change db:" + str(res))

    set_session('ctl', sn)

    return jsonify({
        'err': 0
    })


@wx_http_route.route('/location', methods=["GET"])
@try_catch
def location():
    device_type = request.args.get('device_type', '')
    sn = request.args.get('sn', get_session('ctl'))
    openid = get_token()

    if device_type == '0':  # P9
        ThirdService.inner_service(sn, 'location', [
            sn,
            openid
        ], False)
    elif device_type == '1':  # P8
        ThirdService.inner_service(sn, 'location', [
            sn,
            openid
        ], False)

    return jsonify({'err': 0})


@wx_http_route.route('/get_points', methods=["GET"])
@try_catch
def get_points():
    main_sn = get_session('ctl')
    print(main_sn)
    device_type = request.args.get('device_type', '')
    sn = request.args.get('sn', main_sn)
    limit = int(request.args.get('limit', 30))
    start_time = request.args.get('start_time', '')
    end_time = request.args.get('end_time', '')

    if device_type == '0':  # P9
        need = {
            'client_time': 1,
            'point': 1,
            'network_type': 1,
            'address': 1
        }
        sort_field = 'client_time'
    elif device_type == '1':  # P8
        need = {
            'serverTime': 1,
            'point': 1,
            'address': 1
        }
        sort_field = 'serverTime'
    else:
        need = {
            'serverTime': 1,
            'type': 1,
            'point': 1,
            'address': 1
        }
        sort_field = 'serverTime'

    where = {"sn": sn}

    if start_time:
        int_start_time = TIME.str_to_time(start_time)
        print("int_start_time=" + str(int_start_time))
        where["client_time"] = {
            '$gte': int_start_time
        }
    if end_time:
        int_end_time = TIME.str_to_time(end_time)
        print("int_end_time=" + str(int_end_time))
        where["client_time"] = {
            '$lte': int_end_time
        }

    print("device_type", device_type)
    print(need)
    print(sort_field)
    location_obj_arr = mongo_service.select_colum(WAY_POINT, where, need).sort([(sort_field, DESCENDING)]).limit(limit)
    point_info_arr = []
    for item in location_obj_arr:
        del item['_id']
        if 'serverTime' in item:
            item['client_time'] = item['serverTime']
        point_info_arr.append(item)

    logger.info('point_info_arr----' + json.dumps(point_info_arr))

    return jsonify({
        'err': 0,
        'list': point_info_arr
    })


@wx_http_route.route('/get_signature', methods=['GET', 'OPTIONS', 'POST'])
@try_catch
def get_signature():
    openid = get_token()
    print('openid', openid)
    timestamp = int(time.time())
    url = request.referrer
    now = str(time.time())
    m2 = hashlib.md5()
    m2.update(('tao' + now).encode('utf-8'))

    nonce_str = m2.hexdigest()
    ticket_response = redis_service.client.jsapi.get_ticket()
    signature = redis_service.client.jsapi.get_jsapi_signature(
        nonce_str,
        ticket_response['ticket'],
        timestamp,
        url
    )
    return jsonify({
        'appId': WX.get('appid'),
        'nonceStr': nonce_str,
        'timestamp': timestamp,
        'url': url,
        'signature': signature,
    })


@wx_http_route.route('/add_voice', methods=['GET', 'OPTIONS', 'POST'])
@try_catch
def add_voice():
    print(request.args.get('openId'))
    print(request.args.get('content'))
    return jsonify({
        'device': '868403031127308',
        'type': 'p9',
    })


@wx_http_route.route('/set_model', methods=['GET', 'OPTIONS', 'POST'])
@try_catch
def set_model():
    model = int(request.form.get('model'))
    device_id = request.form.get('device_id')
    openid = request.form.get('open_id')
    data = {
        "status.s_model": model
    }
    where = {
        'sn': device_id
    }
    print(data)
    print(where)
    res1 = mongo_service.update('settings', where, {'$set': data}, True)
    print(res1)

    socketIo.emit('set_model', model, room=get_sid_by_openid(openid), namespace=namespace)

    if model == 2:
        cmd = 's_ls'
    else:
        cmd = 'u_ls'

    res = ThirdService.inner_service(device_id, cmd, [
        openid, device_id
    ])
    logger.info("loc res:" + str(res))

    return jsonify({
        'err': 0
    })


def get_sid_by_openid(openid):
    sid = redis.hget(openid, 'sid')
    if not sid:
        return ''

    return sid.decode()


@wx_http_route.route('/upload_voice_msg', methods=['GET', 'OPTIONS', 'POST'])
@try_catch
def upload_voice_msg():
    url = request.form.get('url')
    device_id = request.form.get('device_id')
    openid = request.form.get('open_id')
    timestamp = int(request.form.get('time'))

    add_one_message(openid, device_id, url, 2, timestamp)

    room = get_sid_by_openid(openid)
    if room:
        socketIo.emit('self_message', {
            "content": url,
            "sender": device_id,
            "time": timestamp,
            "type": 2
        }, room, namespace=namespace)

        socketIo.emit('upload_voice_msg', url, room=room, namespace=namespace)

    return jsonify({
        'err': 0
    })


# @wx_http_route.route('/upload_ps', methods=['GET', 'OPTIONS', 'POST'])
# @try_catch
# def upload_ps():
#     url = request.form.get('url')
#     device_id = request.form.get('device_id')
#     openid = request.form.get('open_id')
#     timestamp = int(request.form.get('timestamp', time.time()))
#
#     # socketIo.emit('upload_ps', url, room=get_sid_by_openid(openid), namespace=namespace)
#
#     message_type = 3
#     add_one_message(device_id, openid, url, message_type, timestamp)
#     # sid = redis.hget(openid, 'sid')
#     # if sid:
#     #     sid = sid.decode()
#     #     print("sid=" + sid)
#     #     msg_content = {"content": url, "sender": device_id, "time": int(time.time()), "type": message_type}
#     #     socketIo.emit('self_message', msg_content, sid, namespace=namespace)
#
#     return jsonify({
#         'err': 0
#     })


@wx_http_route.route('/get_scan_info', methods=['GET', 'OPTIONS', 'POST'])
@try_catch
def get_scan_info():
    return jsonify({
        'device': '868403031127308',
        'type': 'p9',
    })


@wx_http_route.route('/get_device_info', methods=['GET'])
@try_catch
def get_device_info():
    sn = request.args.get('sn', '')
    if not sn:
        raise BaseException('no sn')

    device_info = mongo_service.find_one('devices', {
        'sn': sn
    })
    return jsonify({
        "info": mongo_service.toJsonStr(device_info)
    })


@wx_http_route.route('/tie_device', methods=["GET"])
@try_catch
def tie_device():
    openid = get_token()
    if not openid:
        print('no openid')
        raise 3

    device_sn = request.args.get("sn", '')
    print(device_sn)
    nicky_name = request.args.get("nicky_name", '')
    print(nicky_name)
    device_type = request.args.get("device_type", 0)
    print(device_type)
    if not device_sn:
        raise ResponseError('请填写sn')

    where = {
        "sn": device_sn
    }
    device_info = mongo_service.find_one('devices', where)
    if not device_info:
        device_info = {}
    ctl = device_info.get('ctl', '')
    users = device_info.get('users', {})
    if ctl:
        print('设备已经被绑定')
        raise ResponseError('设备已经被绑定')

    ctl = openid

    users[openid] = {}
    data = {
        'ctl': ctl,
        'sn': device_sn,
        'update_time': datetime.datetime.now(),
        'create_time': datetime.datetime.now(),
        'type': device_type,
        'users': users
    }
    res1 = mongo_service.update('devices', where, {'$set': data}, True)

    where = {
        "openid": openid
    }
    user_info = mongo_service.find_one('users', where)
    ctl = user_info.get('ctl', '')
    devices = user_info.get('devices', '')
    if not ctl:
        ctl = device_sn

    print(nicky_name)

    if not devices:
        devices = dict()

    devices[device_sn] = {
        'name': nicky_name
    }

    data = {
        'ctl': ctl,
        'devices': devices
    }
    res2 = mongo_service.update('users', where, {'$set': data})

    user_info = mongo_service.find_one('users', {
        "openid": openid
    })

    mongo_service.update(
        'family',
        {'sn': device_sn},
        {
            "$set": {
                'sn': device_sn,
                openid: {
                    'nick_name': user_info['nickname'],
                    'phone': ''
                }
            }
        },
        True
    )

    if res1 and res2:
        return jsonify({"err": 0})

    return jsonify({"err": 1, "msg": "添加失败"})


# /wx/wechat?signature=bc55d1d3482d2449785c3e6d29be9aebf73dc077&echostr=1975890682876574651&timestamp=1540370723&nonce=49262811
@wx_http_route.route('/wechat', methods=['GET', 'POST'])
@try_catch
def wechat():
    if request.method == 'GET':
        echo_str = request.args.get('echostr', '')
        if echo_str:
            return make_response(echo_str)

    signature = request.args.get('signature', '')
    timestamp = request.args.get('timestamp', '')
    nonce = request.args.get('nonce', '')
    encrypt_type = request.args.get('encrypt_type', 'raw')
    msg_signature = request.args.get('msg_signature', '')
    openid = ''
    if 'openid' in request.args:
        openid = request.args.get('openid', '')
        print("OpenId：" + openid)
    try:
        check_signature('123456', signature, timestamp, nonce)
    except InvalidSignatureException:
        print("dddddddddddddddddddd")
        abort(403)

    print("encrypt_type=" + encrypt_type)

    # POST request
    if encrypt_type == 'raw':
        # plaintext mode
        msg = parse_message(request.data)

        reply = None
        if msg.type == 'text':
            pass
            # if msg.content == '1':
            #     reply = create_reply("设备列表实现中，敬请期待", msg)
            # elif msg.content == '2':
            #     reply = create_reply("远程监控实现中，敬请期待", msg)
            # elif msg.content == '3':
            #     reply = create_reply("统计信息实现中，敬请期待", msg)
            # else:
            #     reply = create_reply(msg_list, msg)
        else:
            if msg.type == "event":
                print('msg.event = ' + msg.event)
                if msg.event == "subscribe":
                    reply = create_reply("关注成功", msg)
                elif msg.event == "scan":
                    print("扫码推过来了：" + msg)
                    reply = create_reply('消息推过来了', msg)
                    return reply.render()
                elif msg.event == "scancode_waitmsg":
                    scanResult = msg.scan_code_info.get('ScanResult')
                    # scan_json = json.loads(scanResult)
                    print("消息接收中扫码过来了：" + scanResult)
                    reply = create_reply('消息推过来了', msg)
                    return reply.render()
                elif msg.event == "view":
                    # active_device_sn = None
                    # if session.get("active_device") is not None:
                    #     active_device_sn = session.get("active_device")
                    # else:
                    #     userId = msg._data.get("FromUserName")
                    #     active_device_sn = TabletService().get_active_device()
                    #     session.set("active_device", active_device_sn)
                    # if active_device_sn is not None and msg._data.get("EventKey") == WX.get("auth_url"):
                    #     session.set("url_redirect", "/device_map?sn={}".format(active_device_sn))
                    # elif active_device_sn is not None and msg._data.get("EventKey") == WX.get("chat_auth_url"):
                    #     session.set("url_redirect", "/record?sn={}".format(active_device_sn))
                    reply = create_reply('消息推过来了', msg)
                elif msg.event == "location":
                    msg_list = ""

                    if not openid:
                        reply = create_reply("请先关注公众号，体验更多功能", msg)
                    else:
                        info = mongo_service.find_one('users', {
                            "openid": openid
                        })
                        ctl = info.get('ctl', '')
                        if not ctl:
                            reply = create_reply("请先关注公众号，体验更多功能", msg)
                        else:
                            MessageList = [
                                "欢迎进入pbani设备管理微信公众号,",
                            ]
                            if type(MessageList) == list:
                                hour = int(datetime.datetime.now().strftime('%M'))
                                if hour > 18:
                                    MessageList.append('晚上好！')
                                elif hour > 13:
                                    MessageList.append('下午好！')
                                elif hour > 11:
                                    MessageList.append('中午好！')
                                elif hour > 6:
                                    MessageList.append('早上好！')

                                for tempChar in MessageList:
                                    msg_list += tempChar + '\n\r'
                            reply = create_reply(msg_list, msg)

        if not reply:
            return make_response("")
        else:
            return make_response(reply.render())
    else:
        crypto = WeChatCrypto('123456', AES_KEY, APPID)
        try:
            msg = crypto.decrypt_message(
                request.data,
                msg_signature,
                timestamp,
                nonce
            )
        except (InvalidSignatureException, InvalidAppIdException):
            abort(403)
        else:
            print(msg, 121212)
            msg = parse_message(msg)
            if msg.type == 'text':
                reply = create_reply(msg.content, msg)
            else:
                reply = create_reply('Sorry, can not handle this for now', msg)
            return crypto.encrypt_message(reply.render(), nonce, timestamp)


@wx_http_route.route('/del_device', methods=['GET'])
@try_catch
def del_device():
    openid = get_token()
    device_sn = request.args['sn']
    print(openid)
    print(device_sn)
    if not device_sn:
        raise BaseException('no sn')

    update_data = {}
    user_info = mongo_service.find_one('users', {
        "openid": openid
    })

    devices = user_info.get('devices', {})
    ctl = ''
    for key in list(devices.keys()):
        if key == device_sn:
            print(devices)
            del devices[key]
        else:
            ctl = key

    print(devices)
    print("ctl:" + ctl)

    if user_info['ctl'] == device_sn:
        update_data['ctl'] = ctl

    update_data['devices'] = devices
    print(update_data)
    res = mongo_service.update('users', {
        "openid": openid
    }, {
                                   '$set': update_data
                               })
    print(res)

    update_data = {}
    device_info = mongo_service.find_one('devices', {
        "sn": device_sn
    })
    print("device_sn:" + device_sn)
    users = device_info.get('users', {})
    ctl = ''
    for key in list(users.keys()):
        if key == openid:
            del users[key]
        else:
            ctl = key

    print(users)
    print("ctl:" + ctl)

    # if users['ctl'] == openid:
    #     users['ctl'] = ctl

    update_data['users'] = users
    update_data['ctl'] = ctl
    print(update_data)
    res = mongo_service.update('devices', {
        "sn": device_sn
    }, {
                                   '$set': update_data
                               })
    print(res)

    res = ThirdService.inner_service(device_sn, "off_line", [
        device_sn
    ])
    logger.info("off_line res:" + str(res))

    return jsonify({
        'err': 0
    })


@wx_http_route.route('/lock_device', methods=['GET'])
@try_catch
def lock_device():
    sn = request.args.get("sn")
    mode = request.args.get("mode")

    if not sn:
        raise BaseException('no sn')

    if not mode:
        mode = 0

    res = ThirdService.inner_service(sn, 'set_model', [
        get_token(),
        sn,
        mode
    ])

    logger.info("lock_device :" + str(res))
    # res_json = json.loads(res)
    # if 'err' in res_json and res_json['err'] == 0:
    #     mongo_service.update('devices', {'sn': sn}, {'$set': {'status': 2}})
    return jsonify(res)


def get_ctl():
    sn = get_session('ctl')
    if not sn:
        raise BaseException('no ctl')


@wx_http_route.route('/change_screen', methods=['GET'])
@try_catch
def change_screen():
    sn = request.args.get("sn")
    mode = request.args.get("mode")

    if not sn:
        raise BaseException('no sn')

    if not mode:
        mode = 0

    res_json = third_service.browser_get('unlock_screen' if mode == 2 else 'lock_screen', {
        'deviceId': sn
    })

    if 'err' in res_json and res_json['err'] == 0:
        mongo_service.update('devices', {'sn': sn}, {'$set': {'status': 2}})
    return jsonify(res_json)


@wx_http_route.route('/voice_monitor', methods=['GET'])
@try_catch
def voice_monitor():
    sn = request.args.get("sn")
    if not sn:
        raise BaseException('no sn')
    device_type = int(request.args.get("device_type", 0))

    if device_type == 0:
        res = third_service.browser_get('send', {
            'type': third_service.RECORDING_SOUND,
            'deviceId': sn
        })
    else:
        res = ThirdService.inner_service(sn, 'monitor_voice', [
            sn,
            get_token(),
            5
        ])

    return jsonify(res)


def change_device_name(open_id, sn, device_name):
    mongo_service.update('users', {
        'openid': open_id
    }, {'$set': {
        'devices.%s.name' % (sn, ): device_name
    }})


@wx_http_route.route('/update_device_info', methods=['GET'])
@try_catch
def update_device_info():
    sn = request.args.get("sn")
    if not sn:
        raise BaseException('no sn')
    open_id = get_token()

    logger.info("open_id=" + str(open_id))

    device_name = str(request.args.get("device_name", ""))
    if device_name:
        change_device_name(open_id, sn, device_name)

    result = {"err": 0}

    return jsonify(result)


@wx_http_route.route('/device_status', methods=['GET'])
@try_catch
def get_device_status():
    sn = request.args.get('sn', '')
    print(sn)
    if not sn:
        raise BaseException('no sn')

    hash_val = redis_service.redis.hget('tao.online', sn)
    if hash_val is not None:
        val = 1
    else:
        val = 0

    device_screen_state = 0
    model_val = 0
    result = mongo_service.find_one('settings', {
        'sn': sn
    })
    if result and 'status' in result:
        if 'device_screen_state' in result['status']:
            if result['status']['device_screen_state'] == "on":
                device_screen_state = 1
        if 's_model' in result['status']:
            model_val = result['status']['s_model']

    res = {
        "is_online": val,
        "model_val": model_val,
        "screen_is_on": device_screen_state
    }

    print(res)

    return jsonify(res)


@wx_http_route.route('/get_msg_list', methods=['GET'])
@try_catch
def get_msg_list():
    device_sn = request.args.get('sn', '')
    print(device_sn)
    if not device_sn:
        raise Exception("获取聊天记录列表错误")

    result = third_service.browser_get('last_message', {
        'days': 11,
        'deviceId': device_sn
    })
    print(result)
    if "err" in result and result.get("err") == 0:
        return jsonify(result)
    else:
        raise Exception("获取聊天记录列表错误")


def change_resolving(path):
    im = Image.open(path)

    w, h = im.size

    edge = [w, h]

    larger_index = 0
    if w < h:
        larger_index = 1

    larger_val = edge[larger_index]

    if larger_val > 960:
        x = 960 / larger_val
    else:
        return path

    out = im.resize((int(edge[0] * x), int(edge[1] * x)), Image.ANTIALIAS)
    path_arr = path.split("/")
    path_arr[-1] = "re_" + path_arr[-1] + ".jpg"
    new_path = '/'.join(path_arr)
    print(new_path)
    out.save(new_path)
    return new_path


@wx_http_route.route('/tmp_img', methods=['GET'])
@try_catch
def tmp_img():
    device_sn = request.args.get('sn', '')
    device_type = int(request.args.get('device_type', 0))
    server_id = request.args.get('server_id', '')
    if not device_sn:
        raise Exception("1")
    if not server_id:
        raise Exception("2")

    access_token = redis_service.get_access_token()
    print("access_token=" + access_token)
    url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=%s&media_id=%s" % (access_token, server_id)
    http = urllib3.PoolManager()
    response = http.request('GET', url)
    file_name = 'tmp_img_' + str(int(time.time())) + '_' + device_sn
    path = '/tmp/' + file_name
    with open(path, 'wb') as f:
        f.write(response.data)

    path = change_resolving(path)

    # 图片的path 改它的分辨率
    bucket = third_service.cos.get_bucket(QCloud.get('bucket'))
    push_res = bucket.upload_file(
        real_file_path=path,
        file_name=file_name + '.jpg', dir_name=QCloud.get('dir'))
    url = json.loads(push_res.replace("'", '"'))['access_url']

    if device_type == 0:
        err = 0
    else:
        ThirdService.inner_service(device_sn, 'tmp_img', [
            device_sn,
            get_token(),
            url
        ])
        err = 0

    result = {"err": err, "url": url}
    return jsonify(result)

# template_id = "tp80iNSBFsTPObqK1NJ2zN3CxcTSMUZLnmLjSXt4rhY"
